import time
import urllib.parse
from requests import Session


class TestShop:
    base_url = 'http://47.107.116.139/phpwind'
    session = Session()

    def test_01(self):
        # 获取csrf_token
        global token
        resp = self.session.get(self.base_url)
        token = resp.cookies.get("csrf_token")  # 获取cookies

        assert token

    def test_02(self):
        # 登录
        global back_url
        headers = {
            'Accept': 'application/json, text/javascript, /; q=0.01',
            'X-Requested-With': 'XMLHttpRequest',
        }
        data = {
            'username': 'msjy2024',
            'password': 'msjy2024',
            'csrf_token': token,
            'backurl': self.base_url
        }
        resp = self.session.post(self.base_url + '/index.php?m=u&c=login&a=dorun', headers=headers, data=data)
        assert "success" in resp.text
        back_url = urllib.parse.unquote(resp.json()['referer'])

    def test_03(self):
        # 获取cookies
        resp = self.session.get(back_url)
        assert 'msjy2024' in resp.text

    def test_04(self):
        # 发帖
        global tid

        content = f'msjy_{time.time()}'
        data = {
            'fid': 2,
            'atc_title': content,  # 标题不可重复
            'atc_content': content,  # 内容不可重复
            'csrf_token': token,
            'reply_notice': 1
        }
        resp = self.session.post(self.base_url + '/index.php?c=post&a=doadd&_json=1', data=data)
        assert 'success' in resp.text
        url = urllib.parse.unquote(resp.json()['referer'])
        tid = urllib.parse.parse_qs(url)['http://47.107.116.139/phpwind/read.php?tid'][0]

    def test_05(self):
        # 回帖
        time.sleep(4)
        data = {
            'atc_content': f'msjy回帖_{time.time()}',  # 内容不可重复
            'csrf_token': token,
            'tid': tid
        }
        resp = self.session.post(self.base_url + '/index.php?c=post&a=doreply&_getHtml=1', data=data)
        assert 'editor_content' in resp.text
